package com.iterceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.echo.fm.content.systemAction.model.SystemAction;
import com.echo.fm.log.system.ISystemLogService;
import com.echo.fm.log.system.model.SystemLog;
import com.echo.fm.platform.auth.IAuthService;
import com.echo.fm.platform.auth.model.RoleAuth;
import com.echo.fm.platform.auth.model.SystemUser;
import com.echo.fm.user.role.model.Role;
import com.echo.util.impl.HeaderParser;

public class AuthorityInterceptor implements HandlerInterceptor {
	@Autowired()
	@Qualifier("authService")
	IAuthService authService;

	@Autowired
	@Qualifier("systemLogService")
	ISystemLogService systemLogService;

	private static final List<String> filterNoList = Arrays.asList("/Manager/web", "/Manager/wxproxy",
			"/Manager/redirect", "/Manager/redirecturl", "/Manager/web/loginPage", "/Manager/web/login",
			"/Manager/web/json/nologin", "/Manager/web/traffic/loginPage"

	);
	private static final List<String> keyList = Arrays.asList("");

	private static final List<String> basePermissions = Arrays.asList("");

	public void setAuthService(IAuthService authService) {
		this.authService = authService;
	}

	public void setSystemLogService(ISystemLogService systemLogService) {
		this.systemLogService = systemLogService;
	}

	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = HeaderParser.getToken(request);

		boolean isAbleRequest = handler instanceof HandlerMethod;
		boolean isAuthenticated = token != null && request.getSession().getAttribute(token) != null;
		boolean flag = false;
		// 免权限校验
		boolean isNoFilter = false;
		String uri = request.getRequestURI();
		for (String item : filterNoList) {
			if (trim(uri).equals(item)) {
				isNoFilter = true;
				break;
			}
		}

		String accessToken = request.getHeader("accessToken");
		Set<SystemAction> permissionSet = null;
		String user_agent = request.getHeader("user_agent");
		if (isAuthenticated && isAbleRequest) {
			SystemLog systemLog = new SystemLog();
			systemLog.setCilentIp(HeaderParser.getIpAddr(request));

			systemLog.setUser_agent(user_agent);
			systemLog.setRequestMothed(request.getMethod());
			systemLog.setOperateType(0);
			systemLog.setRequestUrl(request.getRequestURI());
			systemLog.setSessionId(request.getRequestedSessionId());
			permissionSet = (Set<SystemAction>) request.getSession().getAttribute("permissionSet");
			SystemUser user = (SystemUser) request.getSession().getAttribute(token);
			// request.setAttribute("permissionRoot",
			// Constants.PERMISSION_ROOT_ID);

			if (permissionSet == null) {
				permissionSet = new HashSet<SystemAction>();
				if (user != null && user.getSuperManager() == SystemUser.IS_SUPER_MANAGER) {
					List<SystemAction> salist = authService.getAllSystemActions();
					permissionSet.addAll(salist);
				} else {
					List<RoleAuth> roleAuthList = new ArrayList<RoleAuth>();
					List<Role> roleList = authService.searcheRoleList(user);
					if (roleList != null) {
						for (Role role : roleList) {
							roleAuthList = authService.listRoleAuth(role.getId());
							if (roleAuthList != null) {
								for (RoleAuth ra : roleAuthList) {

									permissionSet.add(ra.getPermission());

								}
							}
						}
					}
				}

				permissionSet.addAll(convert2PermissionEntity(basePermissions));
				request.getSession().setAttribute("permissionSet", permissionSet);

			}
			if (permissionSet != null) {
				for (SystemAction systemAction : permissionSet) {

					if (systemAction.getUrl() == null || "".equals(systemAction.getUrl())) {

					} else {
						if (trim(systemAction.getUrl()).equals(trim(request.getRequestURI()))) {
							flag = true;
							break;
						}
					}
				}

			}
			if (flag || isNoFilter) {
				systemLog.setUsername(user.getName());
				systemLogService.createSystemLog(systemLog);
				return true;
			} else {
				if (request.getHeader("X-Requested-With") != null) {
					request.getRequestDispatcher("/web/json/nopremission").forward(request, response);
				} else {
					request.getRequestDispatcher("/WEB-INF/pages/platform/nopremission.jsp").forward(request, response);
				}
				return false;
			}
		} else if (isNoFilter && isAbleRequest) {
			if ("/Manager/web/login".equals(request.getRequestURI())) {
				SystemLog systemLog = new SystemLog();
				systemLog.setCilentIp(request.getRemoteAddr());
				systemLog.setRequestMothed(request.getMethod());
				systemLog.setOperateType(0);
				systemLog.setRequestUrl(request.getRequestURI());
				systemLog.setSessionId(request.getRequestedSessionId());
				systemLog.setUsername(request.getParameter("username"));
				systemLogService.createSystemLog(systemLog);
			}
			return true;
		} else if (accessToken != null && keyList.contains(accessToken)) {
			request.setAttribute("token_valid", true);
			return true;
		} else {
			if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
				request.getRequestDispatcher("/web/json/nologin").forward(request, response);
			} else {
				request.getRequestDispatcher("/WEB-INF/pages/platform/login.jsp").forward(request, response);
			}
			return false;
		}
	}

	// private Collection<? extends SystemAction>
	// conver2PermissionEnity(List<String> basepermissions2) {
	// return null;
	// }

	@SuppressWarnings("unused")
	private Collection<? extends SystemAction> convert2PermissionEntity(List<String> basepermissions) {
		List<SystemAction> saList = new ArrayList<SystemAction>();
		if (basepermissions != null && basepermissions.size() > 0) {
			for (String permission : basepermissions) {

				SystemAction act = new SystemAction();
				act.setUrl(permission);
				// act.setSuper_id(Constants.PERMISSION_ROOT_ID);
				act.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				saList.add(act);

			}
		}
		return saList;
	}

	private String trim(String param) {
		if (param.endsWith("/")) {
			return param.substring(0, param.length() - 1);
		}
		return param;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
